package maven;

import com.me.common.util.io.IoUtils;

import java.io.*;

/**
 * gradle cache 中的依赖转存到 maven本地仓库
 *
 * @author bin.yin
 */
public class Gradle2Maven {

    private static final String MAVEN_OUTPUT_DIR = "/maven";

    private static final String JAR_SUFFIX = ".jar";
    private static final String SOURCE_SUFFIX = "-sources.jar";
    private static final String POM_SUFFIX = ".pom";

    private static final String GRADLE_CACHE_HOME_DIR;
    static {
        GRADLE_CACHE_HOME_DIR = System.getenv("GRADLE_USER_HOME");
    }
    private static final String GRADLE_CACHE_FILE_DIR = GRADLE_CACHE_HOME_DIR + "/caches/modules-2/files-2.1";

    public static void main(String[] args) {
        File gradleCacheFilesDir = new File(GRADLE_CACHE_FILE_DIR);
        File[] gradleCacheDirs = gradleCacheFilesDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if(file.isDirectory()){
                    return true;
                }
                return false;
            }
        });

        for (File depGroupDir : gradleCacheDirs) {
            // 找到缓存中的依赖库的每一个组目录
            String groupName = depGroupDir.getName();
            if (groupName.contains(MAVEN_OUTPUT_DIR)) {
                // 对目标目录做一个例外，防止自己的目录被覆盖
                continue;
            }
            try {
                for (File depArtifactDir : depGroupDir.listFiles()) {
                    // 遍历组内的各种依赖包目录
                    String artifactName = depArtifactDir.getName();
                    if(depArtifactDir.isFile()){
                        System.out.println("FOR: skip File not Directory: " + depArtifactDir);
                        continue;
                    }
                    for (File depVersionDir : depArtifactDir.listFiles()) {
                        // 遍历找到依赖包的每一个版本目录
                        String depVersionName = depVersionDir.getName();
                        String outputDir = MAVEN_OUTPUT_DIR + File.separator + groupName.replace(".", File.separator)
                                + File.separator + artifactName + File.separator + depVersionName;
                        new File(outputDir).mkdirs();
                        findAndCopyDepLibs(depVersionDir, outputDir);
                    }
                }
            } catch (Exception e) {
                //TODO: handle exception
                e.printStackTrace();
                throw e;
            }
        }

        System.out.println("\nGradle远程依赖Cache转换为本地Maven目录的操作已完成。");
    }


    /** 遍历目录内包括下级目录中所有的文件，并全部输出到指定目录 */
    private static void findAndCopyDepLibs(File fromDir, String outputDir) {
        for (File file : fromDir.listFiles()) {
            if (file.isDirectory()) {
                findAndCopyDepLibs(file, outputDir);
            } else {
                File outputFile = new File(outputDir, file.getName());
                util_copyFileUsingFileStreams(file, outputFile);
            }
        }
    }

    /**
     * 复制文件
     * @param source
     * @param dest
     */
    private static void util_copyFileUsingFileStreams(File source, File dest) {
        InputStream input = null;
        OutputStream output = null;
        try {
            if (dest.exists()) {
                return;
            }

            System.out.println("copy file: " + source.getAbsolutePath());
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) != -1) {
                output.write(buffer, 0, length);
            }
            output.flush();

            // 如果是jar，复制出 pom
            if (source.getName().endsWith(JAR_SUFFIX) && !source.getName().endsWith(SOURCE_SUFFIX)) {
                System.out.println("copy pom.xml");

                // artifactId：
                String artifactId = source.getParentFile().getParentFile().getParentFile().getName();
                // groupId：
                String groupId = source.getParentFile().getParentFile().getParentFile().getParentFile().getName();
                IoUtils.copyFileInJar(source.getAbsolutePath(), "META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml",
                        dest.getParent() + File.separator + dest.getName().replace(JAR_SUFFIX, POM_SUFFIX));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
